import axios from "axios";
import {
    Message
} from "element-ui";
// 创建axios实例
const service = axios.create({
    timeout: 60000 // 请求超时时间
});
axios.defaults.withCredentials = true

// request拦截器
service.interceptors.request.use(
    config => {
        config.headers["Content-Type"] = 'application/json;charset=UTF-8';
        return config;
    },
    error => {
        Promise.reject(error);
    }
);
// respone拦截器
service.interceptors.response.use(
    response => {
        /**
         * code为非200是抛错 可结合自己业务进行修改
         */
      
        return response
    },
    error => {
        return Promise.reject(error);
    }
);

// get请求
async function get(url) {
    const token = sessionStorage.getItem("TOKEN") || "";
    try {
        const requestConfig = {
            headers: {
                "accessToken": token
            }
        };
        const urlStr = `${url}`;
        const response = await axios.get(urlStr, requestConfig);
        if (response.data.statusCode == 998) {
            Message.error("Token过期，请重新登录!");
            return Promise.reject("Token过期，请重新登录");
        } else {
            return response.data;
        }
    } catch (error) {
        Message.error("服务器异常!");
    } finally {}
}
// post请求
async function post(url, param) {
    try {
        const requestConfig = {
            headers: {
                "Content-Type": "application/json",
                responseType: "json",
                "accessToken": token
            }
        };

        const urlStr = `${url}`;
        const response = await service.post(
            urlStr,
            JSON.stringify(param),
            requestConfig
        );
        if (response.data.statusCode == 200) {
            return response.data;
        } else {
            return Promise.reject("Token过期，请重新登录");
        }
    } catch (error) {
        Message.error("服务器异常!");
    } finally {}
}
// formData-post请求
async function formDataType(url, param) {
    const token = sessionStorage.getItem("TOKEN") || "";
    try {
        const requestConfig = {
            headers: {
                "Content-Type": "multipart/form-data",
                responseType: "json",
                accessToken: token
            }
        };
        const urlStr = `${url}`;
        const response = await axios.post(urlStr, param, requestConfig);
        if (response.data.statusCode == 998) {
            Message.error("Token过期，请重新登录!");
            return Promise.reject("Token过期，请重新登录");
        } else {
            return response.data;
        }
    } catch (error) {
        Message.error("服务器异常!");
    } finally {}
}
export {
    get,
    post,
    formDataType,
    service
};